package LeetCodeHot100TopInterview;

import java.util.Stack;

public class Q150_NiBoLanExpression {

    //逆波兰表达式求值
    //输入：tokens = ["2","1","+","3","*"]
    //输出：9
    //解释：该算式转化为常见的中缀算术表达式为：((2 + 1) * 3) = 9
    //弱智压栈题
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0){
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") ){
                compute(token, stack);
            }else {
                stack.add(Integer.valueOf(token));
            }
        }
        return stack.peek();
    }

    public void compute(String token, Stack<Integer> stack){

        //这里注意顺序问题
        Integer pop2 = stack.pop();
        Integer pop1 = stack.pop();
        if (token.equals("+")){
            stack.add(pop1 + pop2);
        }
        if (token.equals("-")){
            stack.add(pop1 - pop2);
        }
        if (token.equals("*")){
            stack.add(pop1 * pop2);
        }
        if (token.equals("/")){
            stack.add(pop1 / pop2);
        }

    }

    public static void main(String[] args) {
        Q150_NiBoLanExpression fun = new Q150_NiBoLanExpression();
        String[] arg = new String[5];
        arg[0] = "4";
        arg[1] = "13";
        arg[2] = "5";
        arg[3] = "/";
        arg[4] = "+";
        System.out.println(fun.evalRPN(arg));


    }


}
